import https from "https";
import http from "http";
import { Transform } from "stream";

/**
 * base64解析
 * @param dataURL
 * @returns
 */
export function base64Parser(dataURL: string) {
    const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
    if (typeof dataURL !== "string" || !base64Regex.test(dataURL)) {
        return false;
    }
    const stringBase64 = dataURL.replace(base64Regex, "");

    // For nodejs
    if (typeof Buffer !== "undefined" && Buffer.from) {
        return Buffer.from(stringBase64, "base64");
    }
    return false;
}

/**
 * 请求数据
 * @param url
 * @param callback
 */
export function getHttpData(url, callback) {
    (url.substr(0, 5) === "https" ? https : http)
        .request(url, function (response) {
            console.log('response', response)
            if (response.statusCode !== 200) {
                return callback(
                    new Error(
                        `Request to ${url} failed, status code: ${response.statusCode}`
                    )
                );
            }

            const data = new Transform();
            response.on("data", function (chunk) {
                data.push(chunk);
            });
            response.on("end", function () {
                console.log('end', data.read())
                callback(null, data.read());
            });
            response.on("error", function (e) {
                callback(e);
            });
        })
        .end();
}

export function getHttpData2(url, callback) {
    // 发起HTTPS GET请求
    (url.substr(0, 5) === "https" ? https : http).get(url, (res) => {
        // 创建空的Buffer存放图片数据
        const bufferData:any = [];

        res.on('data', (chunk) => {
            // 将每次传输过来的数据添加到Buffer中
            bufferData.push(chunk);
        });

        res.on('end', () => {
            // Buffer合并为完整的图片数据
            const completeImageData = Buffer.concat(bufferData);

            callback(null, completeImageData);
        });
    }).on('error', (err) => {
        callback(err);
    }).end();
}